package io.zhiller.camerademo.ui.component

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.widget.Toast
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCaptureException
import androidx.camera.view.CameraController
import androidx.camera.view.LifecycleCameraController
import androidx.camera.view.PreviewView
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Camera
import androidx.compose.material.icons.filled.Cameraswitch
import androidx.compose.material.icons.filled.PhotoLibrary
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.compose.LocalLifecycleOwner
import io.zhiller.camerademo.utils.CameraUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


@Composable
fun CameraPreviewComp(
  activity: Activity
) {
  // 创建并配置相机控制器
  val controller = remember {
    LifecycleCameraController(
      activity.applicationContext
    ).apply {
      setEnabledUseCases(
        CameraController.IMAGE_CAPTURE or CameraController.VIDEO_CAPTURE
      )
    }
  }

  // 用于保存照片状态的变量
  var savePhotoStates by remember {
    mutableIntStateOf(0)
  }

  // 获取应用上下文
  val ctx = activity.applicationContext

  // 填充整个屏幕的Box，用于显示相机预览和控制按钮
  Box(
    modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center
  ) {
    // 获取当前的生命周期所有者
    val lifecycleOwner = LocalLifecycleOwner.current
    // 创建并配置PreviewView以显示相机预览
    AndroidView(modifier = Modifier.fillMaxSize(), factory = {
      PreviewView(it).apply {
        this.controller = controller
        controller.bindToLifecycle(lifecycleOwner)
      }
    })

    // 创建一个Column来排列相机控制按钮
    Column(
      modifier = Modifier
        .fillMaxHeight()
        .padding(end = 20.dp)
        .align(Alignment.CenterEnd),
      horizontalAlignment = Alignment.CenterHorizontally,
      verticalArrangement = Arrangement.Center
    ) {
      // 创建一个可点击的Box来打开图库
      Box(
        modifier = Modifier
          .clip(RoundedCornerShape(14.dp))
          .size(45.dp)
          .background(color = Color(0x33000000))
          .clickable {
            Intent(
              Intent.ACTION_VIEW, Uri.parse(
                "content://media/internal/images/media"
              )
            ).also {
              activity.startActivity(it)
            }
          }, contentAlignment = Alignment.Center
      ) {
        Icon(
          imageVector = Icons.Default.PhotoLibrary,
          contentDescription = "open gallery",
          tint = MaterialTheme.colorScheme.onPrimary,
          modifier = Modifier.size(26.dp)
        )
      }

      Spacer(modifier = Modifier.height(16.dp))

      // 创建一个可点击的Box来拍照
      Box(
        modifier = Modifier
          .clip(CircleShape)
          .size(60.dp)
          .background(color = Color(0x33000000))
          .clickable {
            CoroutineScope(Dispatchers.Main).launch {
              try {
                CameraUtils.takeAndSavePhoto(
                  ctx,
                  controller,
                  imageInfo = null,
                  onSuccess = { savePhotoStates = 1 },
                  onError = { savePhotoStates = 2 })
              } catch (e: ImageCaptureException) {
                e.printStackTrace()
              }
            }
          }, contentAlignment = Alignment.Center
      ) {
        Icon(
          imageVector = Icons.Default.Camera,
          contentDescription = "take photo",
          tint = MaterialTheme.colorScheme.onPrimary,
          modifier = Modifier.size(26.dp)
        )
      }

      Spacer(modifier = Modifier.height(16.dp))

      // 创建一个可点击的Box来切换前后摄像头
      Box(
        modifier = Modifier
          .clip(RoundedCornerShape(14.dp))
          .size(45.dp)
          .background(color = Color(0x33000000))
          .clickable {
            controller.cameraSelector =
              if (controller.cameraSelector == CameraSelector.DEFAULT_BACK_CAMERA) {
                CameraSelector.DEFAULT_FRONT_CAMERA
              } else {
                CameraSelector.DEFAULT_BACK_CAMERA
              }
          }, contentAlignment = Alignment.Center
      ) {
        Icon(
          imageVector = Icons.Default.Cameraswitch,
          contentDescription = "switch camera",
          tint = MaterialTheme.colorScheme.onPrimary,
          modifier = Modifier.size(26.dp)
        )
      }
    }

    // 根据照片状态显示不同的Toast消息
    when (savePhotoStates) {
      0 -> {}
      1 -> {
        Toast.makeText(ctx, "拍照成功", Toast.LENGTH_SHORT).show()
        savePhotoStates = 0
      }

      2 -> {
        Toast.makeText(ctx, "拍照失败", Toast.LENGTH_SHORT).show()
        savePhotoStates = 0
      }

      else -> {}
    }
  }
}


///**
// * 使用 Compose 实现的相机预览组件
// * 该组件展示了如何使用 CameraX 库在屏幕上显示相机预览，并提供了一个按钮用于拍照
// */
//@Composable
//fun CameraPreviewComp() {
//  // 选择后置摄像头
//  val lensFacing = CameraSelector.LENS_FACING_BACK
//  // 获取当前的 LifecycleOwner，用于管理相机的生命周期
//  val lifecycleOwner = LocalLifecycleOwner.current
//  // 获取当前上下文，用于访问相机提供者
//  val context = LocalContext.current
//  // 构建预览用例，用于显示相机画面
//  val preview = Preview.Builder().build()
//  // 使用 remember 保存预览视图，避免不必要的重组
//  val previewView = remember {
//    PreviewView(context)
//  }
//  // 构建相机选择器，要求特定的镜头方向（后置摄像头）
//  val cameraxSelector = CameraSelector.Builder().requireLensFacing(lensFacing).build()
//  // 使用 remember 保存图像捕获用例，避免不必要的重组
//  val imageCapture = remember {
//    ImageCapture.Builder().build()
//  }
//  // 当镜头方向改变时，重新启动效应，以重新配置相机
//  LaunchedEffect(lensFacing) {
//    // 获取相机提供者，用于管理相机资源
//    val cameraProvider = CameraUtils.getCameraProvider(context)
//    // 解绑所有现有的相机用例
//    cameraProvider.unbindAll()
//    // 将预览和图像捕获用例绑定到生命周期
//    cameraProvider.bindToLifecycle(lifecycleOwner, cameraxSelector, preview, imageCapture)
//    // 将预览的表面提供者设置为预览视图的表面提供者
//    preview.setSurfaceProvider(previewView.surfaceProvider)
//  }
//  // 使用 Box 布局来展示预览视图和拍照按钮
//  Box(contentAlignment = Alignment.BottomCenter, modifier = Modifier.fillMaxSize()) {
//    // 在此处插入预览视图
//    AndroidView({ previewView }, modifier = Modifier.fillMaxSize())
//    // 提供拍照功能的按钮
//    Button(onClick = {
//      CameraUtils.captureAndSaveImage(
//        imageInfo = null,
//        imageCapture = imageCapture,
//        context = context,
//        onSuccess = {
//          println("Success")
//        },
//        onError = {
//          println("Failed")
//        }
//      )
//    }) {
//      Text(text = "Capture Image")
//    }
//  }
//}


///**
// * 使用ImageCapture捕获图像并保存到指定路径
// *
// * @param imageCapture ImageCapture实例，用于捕获图像
// * @param context 上下文，用于访问内容解析器和资源
// */
//private fun captureImage(imageCapture: ImageCapture, context: Context) {
//  // 图像文件名
//  val name = "CameraxImage.jpeg"
//
//  // 创建ContentValues以设置图像文件的元数据
//  val contentValues = ContentValues().apply {
//    put(MediaStore.MediaColumns.DISPLAY_NAME, name)
//    put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
//    put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/CameraX-Image")
//  }
//
//  // 构建ImageCapture.OutputFileOptions对象，用于指定图像保存的位置和元数据
//  val outputOptions = ImageCapture.OutputFileOptions
//    .Builder(
//      context.contentResolver,
//      MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
//      contentValues
//    )
//    .build()
//
//  // 捕获图像并保存到指定位置
//  imageCapture.takePicture(
//    outputOptions,
//    ContextCompat.getMainExecutor(context),
//    object : ImageCapture.OnImageSavedCallback {
//      // 当图像成功保存时调用
//      override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
//        println("Successes")
//      }
//
//      // 当图像保存失败时调用
//      override fun onError(exception: ImageCaptureException) {
//        println("Failed $exception")
//      }
//    })
//}
